/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package im.resources.model;

import im.general.BaseAgent;
import im.general.Config;
import im.node.MobileNodeAgent;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Gnaskky
 */
public class ResourcesDynamicUpdaterBehaviour extends CyclicBehaviour {

    private BaseAgent node;
    private MessageTemplate mt;

    public ResourcesDynamicUpdaterBehaviour(BaseAgent n) {
        this.node = n;
        if( !node.getAID().getLocalName().equals(Config.EVENT_SERVICE_NAME)) {
            ACLMessage wrap_msg = new ACLMessage(ACLMessage.INFORM_REF);
            wrap_msg.addUserDefinedParameter(Config.IM_RMSG_TYPE, Config.IM_RMSG_TYPE);
            this.mt = MessageTemplate.MatchCustom(wrap_msg, true);
        }
    }

    public void action() {

        try {
            block(Config.UPDATE_RESOURCE_FREQ_SEC);

            if( !node.getAID().getLocalName().equals(Config.EVENT_SERVICE_NAME)) {

                ACLMessage msg;
                msg = node.receive(mt);

                if (msg != null ) {
                    if(Config.TRACE_LVL > Config.NIGHTMARE_TR_LVL )
                        System.out.println("[ResourcesDynamicUpdater] " + node.getAID().getName() + " wrapping upd CL size");
                    this.node.setAttachedNodes( ((Integer) msg.getContentObject()).intValue());
                }
            }

            this.node.updateResources();

        } catch (UnreadableException ex) {
            Logger.getLogger(ResourcesDynamicUpdaterBehaviour.class.getName()).log(Level.SEVERE, null, ex);
        }

    }


}
